import { defineStore } from "pinia";
import { store } from "@/store";
import { cacheType } from "./types";
import { constantMenus } from "@/router";
import {cloneDeep, getKeyList} from "@pureadmin/utils";
import { useMultiTagsStoreHook } from "./multiTags";
import {ascending, filterTree, filterNoPermissionTree, handleAsyncRoutes} from "@/router/utils";
import {FunctionMethod} from "@/api/user";
import {FunctionPermission, FunctionType} from "@/config/constDef";
import {usePermissionStore, usePermissionStoreHook} from "@/store/modules/permission";

export const useFunctionStore = defineStore({
  id: "pure-function",
  state: () => ({
    // 所有的TX
    allFunctions: new Array<FunctionMethod>(),
    // 所有的接口TX
    interfaceFunctions: new Array<FunctionMethod>(),
    // 所有的菜单TX
    menuFunctions: new Array<FunctionMethod>(),
    // 所有的按钮TX
    buttonFunctions: new Array<FunctionMethod>(),
  }),
  actions: {
    /** 获取全部的TX  并进行分类 */
    initFunction(funcList: FunctionMethod[]) {
      const functionList = funcList.filter(t => t.permission == FunctionPermission.W)
      this.allFunctions = cloneDeep(functionList);
      this.interfaceFunctions = functionList.filter(n => n.type === FunctionType.interface);
      this.menuFunctions =  functionList.filter(n => n.type === FunctionType.menu);
      this.buttonFunctions = functionList.filter(n => n.type === FunctionType.button);
      this.handMenuList()

    },
    /** 根据菜单的TX 生成新的菜单 */
    handMenuList(){
      console.log(this.menuFunctions);
      const routes = this.menuFunctions.map((n, i) => {
        const p = n.functionID.split(('_'))[1]
        return p ? {
          path: '/' + p.toLowerCase(),
          meta: {
            title: p,
            icon: "lollipop",
            rank: i+100
          },
          children: [
            {
              path: `/${p.toLowerCase()}/index`,
              name: p+ ' page',
              meta: {
                title: p,
                keepAlive: true,
                roles: ["test"],
                auths: ["btn_add", "btn_edit", "btn_delete"]
              }
            }
          ]
        } : null;
      })?.filter(t => t)
      handleAsyncRoutes(cloneDeep(routes));
    },

    /** 清空缓存页面 */
    clearAllCachePage() {
      this.allFunctions = [];
      this.interfaceFunctions = [];
      this.menuFunctions = [];
      this.buttonFunctions = [];
    }
  }
});

export function useFunctionStoreHook() {
  return useFunctionStore(store);
}
